package com.platform.api;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.platform.annotation.LoginUser;
import com.platform.dao.ApiWithdrawMapper;
import com.platform.entity.*;
import com.platform.service.*;
import com.platform.util.ApiBaseAction;
import com.platform.util.ApiPageUtils;
import com.platform.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者: @author Harmon <br>
 * 时间: 2017-08-11 08:32<br>
 * 描述: ApiIndexController <br>
 */
@Api(tags = "会员验证")
@RestController
@RequestMapping("/api/user")
public class ApiUserController extends ApiBaseAction {
    @Autowired
    private ApiUserService userService;
    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private ApiUserTransactionRecordService apiUserTransactionRecordService;

    @Autowired
    private ApiWithdrawService apiWithdrawService;

    @Autowired
    private ApiOrderService apiOrderService;

    @Autowired
    private ApiOrderGoodsService apiOrderGoodsService;

    @Autowired
    private ApiUserLevelService apiUserLevelService;

    /**
     * 发送短信
     */
//    @ApiOperation(value = "发送短信")
//    @PostMapping("smscode")
//    public Object smscode(@LoginUser UserVo loginUser) {
//        JSONObject jsonParams = getJsonRequest();
//        String phone = jsonParams.getString("phone");
//        // 一分钟之内不能重复发送短信
//        SmsLogVo smsLogVo = userService.querySmsCodeByUserId(loginUser.getUserId());
//        if (null != smsLogVo && (System.currentTimeMillis() / 1000 - smsLogVo.getLog_date()) < 1 * 60) {
//            return toResponsFail("短信已发送");
//        }
//        //生成验证码
//        String sms_code = CharUtil.getRandomNum(4);
//        String msgContent = "您的验证码是：" + sms_code + "，请在页面中提交验证码完成验证。";
//        // 发送短信
//        String result = "";
//        //获取云存储配置信息
//        SmsConfig config = sysConfigService.getConfigObject(Constant.SMS_CONFIG_KEY, SmsConfig.class);
//        if (StringUtils.isNullOrEmpty(config)) {
//            return toResponsFail("请先配置短信平台信息");
//        }
//        if (StringUtils.isNullOrEmpty(config.getName())) {
//            return toResponsFail("请先配置短信平台用户名");
//        }
//        if (StringUtils.isNullOrEmpty(config.getPwd())) {
//            return toResponsFail("请先配置短信平台密钥");
//        }
//        if (StringUtils.isNullOrEmpty(config.getSign())) {
//            return toResponsFail("请先配置短信平台签名");
//        }
//        try {
//            /**
//             * 状态,发送编号,无效号码数,成功提交数,黑名单数和消息，无论发送的号码是多少，一个发送请求只返回一个sendid，如果响应的状态不是“0”，则只有状态和消息
//             */
//            result = SmsUtil.crSendSms(config.getName(), config.getPwd(), phone, msgContent, config.getSign(),
//                    DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"), "");
//        } catch (Exception e) {
//
//        }
//        String arr[] = result.split(",");
//
//        if ("0".equals(arr[0])) {
//            smsLogVo = new SmsLogVo();
//            smsLogVo.setLog_date(System.currentTimeMillis() / 1000);
//            smsLogVo.setUser_id(loginUser.getUserId());
//            smsLogVo.setPhone(phone);
//            smsLogVo.setSms_code(sms_code);
//            smsLogVo.setSms_text(msgContent);
//            userService.saveSmsCodeLog(smsLogVo);
//            return toResponsSuccess("短信发送成功");
//        } else {
//            return toResponsFail("短信发送失败");
//        }
//    }


    @ApiOperation(value = "发送短信")
    @PostMapping("smscode")
    public Object smscode(@LoginUser UserVo loginUser) {
        JSONObject jsonParams = getJsonRequest();
        String phone = jsonParams.getString("phone");
        // 一分钟之内不能重复发送短信
        SmsLogVo smsLogVo = userService.querySmsCodeByUserId(loginUser.getUserId());
        if (null != smsLogVo && (System.currentTimeMillis() / 1000 - smsLogVo.getLog_date()) < 1 * 60) {
            return toResponsFail("短信已发送");
        }

        RunResult<String> runResult = SmsUtil.deliver(phone);

        if (runResult.isSuccess()) {
            return toResponsSuccess("短信发送成功");
        } else {
            return toResponsFail("短信发送失败");
        }
    }
    /**
     * 获取当前会员等级
     *
     * @param loginUser
     * @return
     */
    @ApiOperation(value = "获取当前会员等级")
    @PostMapping("getUserLevel")
    public Object getUserLevel(@LoginUser UserVo loginUser) {
        String userLevel = userService.getUserLevel(loginUser);
        return toResponsSuccess(userLevel);
    }


    @ApiOperation(value = "获取当前会员信息")
    @PostMapping("getUserInfo")
    public Object getUserInfo(@LoginUser UserVo loginUser) {
        loginUser = userService.getUserInfo(loginUser);
        return toResponsSuccess(loginUser);
    }


    @ApiOperation(value = "获取当前会员规则")
    @PostMapping("getUserLevelRule")
    public Object getUserLevelRule() {
        return toResponsSuccess(apiUserLevelService.queryRule());
    }


    @ApiOperation(value = "交易明细接口")
    @PostMapping("userTransactionRecordList")
    public Object userTransactionRecordList(@LoginUser UserVo loginUser,
                                            @RequestParam(value = "page", defaultValue = "1") Integer page,
                                            @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Map params = new HashMap();
        params.put("user_id", loginUser.getUserId());
        params.put("page", page);
        params.put("limit", size);
        params.put("sidx", "id");
        params.put("order", "asc");

        //查询列表数据
        Query query = new Query(params);

        List<UserTransactionRecordVo> userTransactionRecordVos = apiUserTransactionRecordService.queryList(query);
        int total = apiUserTransactionRecordService.queryTotal(query);
        ApiPageUtils pageUtil = new ApiPageUtils(userTransactionRecordVos, total, query.getLimit(), query.getPage());

        Map resultMap = Maps.newHashMap();
        resultMap.put("page", pageUtil);
        resultMap.put("totalAccount", loginUser.getTotal_account_format());
        resultMap.put("account", loginUser.getAccount_format());
        resultMap.put("commission", loginUser.getCommission_format());
        return toResponsSuccess(resultMap);
    }


    @ApiOperation(value = "返点明细接口")
    @PostMapping("userTransactionRecordRebateList")
    public Object userTransactionRecordRebateList(@LoginUser UserVo loginUser,
                                            @RequestParam(value = "page", defaultValue = "1") Integer page,
                                            @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Map params = new HashMap();
        params.put("user_id", loginUser.getUserId());
        params.put("page", page);
        params.put("limit", size);
        params.put("sidx", "id");
        params.put("order", "asc");

        //查询列表数据
        Query query = new Query(params);

        List<UserTransactionRecordVo> userTransactionRecordVos = apiUserTransactionRecordService.queryRebateList(query);
        int total = apiUserTransactionRecordService.queryRebateTotal(query);
        ApiPageUtils pageUtil = new ApiPageUtils(userTransactionRecordVos, total, query.getLimit(), query.getPage());

        Map resultMap = Maps.newHashMap();
        resultMap.put("page", pageUtil);
        resultMap.put("totalAccount", loginUser.getTotal_account_format());
        resultMap.put("account", loginUser.getAccount_format());
        resultMap.put("commission", loginUser.getCommission_format());
        return toResponsSuccess(resultMap);
    }

    @ApiOperation(value = "粉丝列表")
    @PostMapping("fansList")
    public Object fansList(@LoginUser UserVo loginUser,
                                            @RequestParam(value = "page", defaultValue = "1") Integer page,
                                            @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Map params = new HashMap();
        params.put("referrer_id", loginUser.getUserId());
        params.put("page", page);
        params.put("limit", size);
        params.put("sidx", "id");
        params.put("order", "asc");
        //查询列表数据
        Query query = new Query(params);

        List<UserVo> fans = userService.queryList(query);
        int total = userService.queryTotal(query);
        ApiPageUtils pageUtil = new ApiPageUtils(fans, total, query.getLimit(), query.getPage());
        return toResponsSuccess(pageUtil);
    }

    @ApiOperation(value = "分销订单列表")
    @PostMapping("fansOrderList")
    public Object fansOrderList(@LoginUser UserVo loginUser,
                           @RequestParam(value = "page", defaultValue = "1") Integer page,
                           @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Map params = new HashMap();
        params.put("user_id", loginUser.getUserId());
        params.put("page", page);
        params.put("limit", size);
        params.put("sidx", "id");
        params.put("order", "asc");
        //查询列表数据
        Query query = new Query(params);

        List<OrderVo> orderEntityList = apiOrderService.queryFansOrderList(query);
        int total = apiOrderService.queryFansOrderTotal(query);
        ApiPageUtils pageUtil = new ApiPageUtils(orderEntityList, total, query.getLimit(), query.getPage());
        //
        for (OrderVo item : orderEntityList) {
            Map orderGoodsParam = new HashMap();
            orderGoodsParam.put("order_id", item.getId());
            //订单的商品
            List<OrderGoodsVo> goodsList = apiOrderGoodsService.queryList(orderGoodsParam);
            Integer goodsCount = 0;
            for (OrderGoodsVo orderGoodsEntity : goodsList) {
                goodsCount += orderGoodsEntity.getNumber();
                item.setGoodsCount(goodsCount);
                item.setOrder_goodss(goodsList);
            }
        }
        return toResponsSuccess(pageUtil);
    }

    @ApiOperation(value = "提现明细")
    @PostMapping("withdrawList")
    public Object withdrawList(@LoginUser UserVo loginUser,
                           @RequestParam(value = "page", defaultValue = "1") Integer page,
                           @RequestParam(value = "size", defaultValue = "10") Integer size) {
        Map params = new HashMap();
        params.put("user_id", loginUser.getUserId());
        params.put("page", page);
        params.put("limit", size);
        params.put("sidx", "id");
        params.put("order", "asc");
        //查询列表数据
        Query query = new Query(params);

        List<WithdrawVo> withdrawVos = apiWithdrawService.queryList(query);
        int total = apiWithdrawService.queryTotal(query);
        ApiPageUtils pageUtil = new ApiPageUtils(withdrawVos, total, query.getLimit(), query.getPage());
        return toResponsSuccess(pageUtil);
    }

//    /**
//     * 绑定手机
//     */
//    @ApiOperation(value = "绑定手机")
//    @PostMapping("bindMobile")
//    public Object bindMobile(@LoginUser UserVo loginUser) {
//        JSONObject jsonParams = getJsonRequest();
//        SmsLogVo smsLogVo = userService.querySmsCodeByUserId(loginUser.getUserId());
//
//        String mobile_code = jsonParams.getString("mobile_code");
//        String mobile = jsonParams.getString("mobile");
//
//        if (!mobile_code.equals(smsLogVo.getSms_code())) {
//            return toResponsFail("验证码错误");
//        }
//        UserVo userVo = userService.queryObject(loginUser.getUserId());
//        userVo.setMobile(mobile);
//        userService.update(userVo);
//        return toResponsSuccess("手机绑定成功");
//    }

    /**
     * 绑定手机
     */
    @ApiOperation(value = "绑定手机")
    @PostMapping("bindMobile")
    public Object bindMobile(@LoginUser UserVo loginUser) {
        JSONObject jsonParams = getJsonRequest();
        String mobile_code = jsonParams.getString("mobile_code");
        String mobile = jsonParams.getString("mobile");

        RunResult runResult = SmsUtil.verify(mobile_code, mobile_code);
        if (runResult.isSuccess()){
            UserVo userVo = userService.queryObject(loginUser.getUserId());
            userVo.setMobile(mobile);
            userService.update(userVo);
            return toResponsSuccess("手机绑定成功");
        } else {
            return toResponsFail(runResult.getMessage());
        }

    }
}